package net.asfun.jvalog.control;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.asfun.jvalog.entity.Sort;
import net.asfun.jvalog.service.CategoryService;
import net.asfun.jvalog.util.RequestUtil;
import net.asfun.jvalog.util.ResponseUtil;
import net.asfun.jvalog.vo.Pager;
import net.asfun.jvalog.mvc.RequestMapping;

public class CategoryController {
	

	@RequestMapping("/category")
	public String index(HttpServletRequest req, Map<String, Object> model) {
		int page = RequestUtil.getIntParam(req, "page");
		Pager pager = new Pager(page);
		model.put("categories", CategoryService.listAll(pager));
		model.put("pager", pager);
		return "categories.html";
	}
	
	@RequestMapping("/category/delete")
	public String delete(HttpServletRequest req, Map<String, Object> model) {
		Long[] ids = RequestUtil.getLongParams(req, "id");
		for (int i=0; i<ids.length; i++) {
			CategoryService.delete(ids[i]);
		}
		return ResponseUtil.feedback("category.delete", req, model);
	}
	
	@RequestMapping("/category/create")
	public String create(HttpServletRequest req, Map<String, Object> model) {
		return "category.html";
	}
	
	@RequestMapping("/category/add")
	public String add(HttpServletRequest req, Map<String, Object> model) {
		String name = RequestUtil.getRequiredParam(req, "name");
		String slogan =  RequestUtil.getStringParam(req, "slogan", name);
		int order = RequestUtil.getIntParam(req, "order");
		Sort sort = new Sort();
		sort.setName(name);
		sort.setSlogan(slogan);
		sort.setOrder(order);
		CategoryService.addCategory(sort);
		
		return ResponseUtil.feedback("category.add", req, model);
	}
	
	@RequestMapping("/category/update")
	public String update(HttpServletRequest req, Map<String, Object> model) {
		Long id = RequestUtil.getLongParam(req, "id");
		String name = RequestUtil.getRequiredParam(req, "name");
		String slogan =  RequestUtil.getStringParam(req, "slogan", name);
		int order = RequestUtil.getIntParam(req, "order");
		Sort sort = new Sort();
		sort.setId(id);
		sort.setName(name);
		sort.setOrder(order);
		sort.setSlogan(slogan);
		CategoryService.update(sort);
		
		return ResponseUtil.feedback("category.update", req, model);
	}
	
	@RequestMapping("/category/edit")
	public String edit(HttpServletRequest req, Map<String, Object> model) {
		Long id = RequestUtil.getLongParam(req, "id");
		model.put("category", CategoryService.getById(id));
		return "category.html";
	}
	

}
